import Taro from '@tarojs/taro';
import interceptors from './interceptors';
import { pageToLogin } from './utils';
import { BIZ_STATUS_CODE } from './enum';
// import { BIZ_STATUS_CODE } from './enum';
// import { pageToLogin } from './utils';

interface RequestParams {
  url: string;
  data?: unknown;
  contentType?: string;
}

interceptors.forEach((interceptor) => Taro.addInterceptor(interceptor));

/**
 * 请求类
 */
class httpRequest {
  baseOptions(
    params: RequestParams,
    method: keyof Taro.request.Method = 'GET',
  ): Promise<CommonResponse<any>> {
    const { url, data } = params;

    let contentType = 'application/json';

    contentType = params.contentType || contentType;

    return new Promise(async (resolve, reject) => {
      let openToken = Taro.getStorageSync('openToken');
      Taro.request({
        url: `${process.env.CS_APP_API}${url}`,
        data,
        method,
        header: {
          'content-type': contentType,
          Cookie: `satoken=${openToken}`,
        },
        success(result: Taro.request.SuccessCallbackResult) {
          // console.log(result, 'result');
          // 业务状态码
          const { code, errMessage } = result.data;
          if (code === BIZ_STATUS_CODE.SUCCESS || code === undefined || code === null) {
            resolve(result.data);
          } else if (
            code === BIZ_STATUS_CODE.AUTHENTICATE ||
            Math.abs(code) === BIZ_STATUS_CODE.EXPIRED_TOKEN
          ) {
            Taro.setStorageSync('authorize', '');
            Taro.setStorageSync('isLogin', false);
            pageToLogin();

            reject('请登录账号');
          } else {
            reject(errMessage || '网络异常请重试');
          }
        },
        fail(error: TaroGeneral.CallbackResult) {
          reject(error);
        },
      });
    });
  }

  get(url: string, data?: unknown) {
    const option = { url, data };

    return this.baseOptions(option);
  }

  post(url: string, data?: unknown, contentType?: string) {
    const params = { url, data, contentType };

    return this.baseOptions(params, 'POST');
  }

  put(url: string, data?: unknown) {
    const option = { url, data };

    return this.baseOptions(option, 'PUT');
  }

  delete(url: string, data?: unknown) {
    // 将 data 转换为 query 参数拼接到 URL 上
    let queryUrl = url;
    if (data && typeof data === 'object') {
      const queryString = Object.entries(data)
        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
        .join('&');
      queryUrl = `${url}${url.includes('?') ? '&' : '?'}${queryString}`;
    }
    const option = { url: queryUrl, data: undefined };

    return this.baseOptions(option, 'DELETE');
  }
}

export default new httpRequest();
